//
//  WBStatusListViewModel.swift
//  Weibo
//
//  Created by apple on 2016/12/4.
//  Copyright © 2016年 yanjun. All rights reserved.
//

import Foundation

// 微博数据列表视图模型
/* 
   父类的选择
 */

private let maxPullTryTimes = 3

class WBStatusListViewModel {
    
    lazy var statusList = [WBStatus]()
    
    // 上拉刷新错误次数
    private var pullupErrorTime = 0
    
    func loadStatus(pullup: Bool, completion: @escaping (_ isSuccess: Bool,_ shouldRefresh: Bool) -> ()) {
        
        // 判断是否是上拉刷新，同时检查刷新错误
        if pullup && pullupErrorTime > maxPullTryTimes {
            completion(true,false)
            return
        }
        
        
        // since_id 取出数组分钟第一条微博的 id
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        
        let max_id = !pullup ? 0 : (statusList.last?.id ?? 0)
        
        WBNetworkManager.shared().statusList(since_id: since_id,max_id: max_id) { (list, isSuccess) in
            
            // 1.字典转模型
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
                
                completion(isSuccess,false)
                
                return
            }
            
            // 2.拼接数据
            
            
            if pullup {
                
                self.statusList += array
            }else{
                // 下拉刷新，应该将结果拼接在数组前面
                self.statusList = array + self.statusList
            }
            
            // 判断上拉刷新的数据量
            if pullup && array.count == 0 {
                
                self.pullupErrorTime += 1
                
                completion(isSuccess, false)
                
            }else{
                
                // 3.完成回调
                
                completion(isSuccess,true)
            }
            
            
            
            
        }
        
        
    }
    
}

